export interface Game {
  board: string[];
  currentPlayer: 'X' | 'O';
  gameActive: boolean;
  winner: string | null;
}

export const createNewGame = (): Game => ({
  board: Array(9).fill(''),
  currentPlayer: 'X',
  gameActive: true,
  winner: null
})

export const makeMove = (game: Game, cellIndex: number): Game => {
  if (!game.gameActive || game.board[cellIndex] !== '') {
    return game
  }

  // 创建新的棋盘状态
  const newBoard = [...game.board]
  newBoard[cellIndex] = game.currentPlayer

  // 检查获胜条件
  const winPatterns = [
    [0, 1, 2], [3, 4, 5], [6, 7, 8], // 行
    [0, 3, 6], [1, 4, 7], [2, 5, 8], // 列
    [0, 4, 8], [2, 4, 6]             // 对角线
  ]

  let winner = null
  let gameActive = true

  for (const pattern of winPatterns) {
    const [a, b, c] = pattern
    if (
      newBoard[a] &&
      newBoard[a] === newBoard[b] &&
      newBoard[a] === newBoard[c]
    ) {
      winner = newBoard[a]
      gameActive = false
      break
    }
  }

  // 检查平局
  if (!winner && newBoard.every(cell => cell !== '')) {
    gameActive = false
  }

  // 切换玩家
  const nextPlayer = gameActive ? (game.currentPlayer === 'X' ? 'O' : 'X') : game.currentPlayer

  return {
    ...game,
    board: newBoard,
    currentPlayer: nextPlayer,
    gameActive,
    winner
  }
}